//
//  PMSideStatisticsHomeController.m
//  XTCloud
//
//  Created by QA on 2017/12/1.
//  Copyright © 2017年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "PMSideStatisticsHomeController.h"

#import "WebServiceCommonRequest.h"
#import "UITableView+Custom.h"
#import "NSDictionary+DataFormat.h"
#import "StringAxisValueFormatter.h"

#import "GEObjectValueTableViewCell.h"
#import "GEProgressBarTableViewCell.h"
#import "AutoTextTableViewCell.h"
#import "PMSideStatisticsHomeCell.h"
#import "DateTimeFormat.h"
#import "GEObjectButton.h"

#import "FXCyclePagerView.h"
#import "FXPageControl.h"
#import "PMSideStatisticsHomeChartCell.h"

#import "MJRefresh.h"
#import "GEDateFromatter.h"
#import "MCConsumeDetailViewController.h"
#import "PMSideStatisticsViewController.h"
#import "PMSideStatisticsSearchViewController.h"

@interface PMSideStatisticsHomeController ()<FXCyclePagerViewDataSource, FXCyclePagerViewDelegate>

@property (nonatomic, strong) IBOutlet GETableView *tableView;

@property (nonatomic,strong) NSMutableArray *stateData;
@property (nonatomic,assign) NSInteger stateContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@property (strong, nonatomic) NSString *searchStartTime;
@property (strong, nonatomic) NSString *searchEndTime;

@end

@implementation PMSideStatisticsHomeController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle:@"砼方量查询"];
        [self addSearchToNavigationItem];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 10)];
    self.stateData = [NSMutableArray array];
    
    //设置默认搜索时间(本月)
    NSString *time = [GEDateFromatter formmatTimeDate:[NSDate date] format:@"yyyy-MM"];
    self.searchStartTime = [NSString stringWithFormat:@"%@-01",time];
    self.searchEndTime = [GEDateFromatter formmatTimeDate:[NSDate date]];
    
    NSString *subTitle = [NSString stringWithFormat:@"以下为%@至%@数据",self.searchStartTime,self.searchEndTime];
    [self setTitle:@"砼方量查询" subtitle:subTitle];
    
    //获取数据
    [self getJobOrderInfoIsReresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateTableStartTime:(NSString*)startTime endTime:(NSString*)endTime
{
    self.searchStartTime = startTime;
    self.searchEndTime = endTime;
    
    NSString *subTitle = [NSString stringWithFormat:@"以下为%@至%@数据",startTime,endTime];
    [self setSubtitle:subTitle];
    [self setTitle:@"砼方量查询" subtitle:subTitle];
    
    [self.stateData removeAllObjects];
    [self.tableView removeAllSaveCell];
    
    self.stateContentState = 0;
    [self.tableView reloadData];
    [self getJobOrderInfoIsReresh];
}

#pragma mark -
#pragma mark IBAction

- (void)searchChargeSelector:(id)sender
{
    PMSideStatisticsSearchViewController *view = [[PMSideStatisticsSearchViewController alloc] init];
    view.backResultDelagate = self;
    AbstractNavigationController *navigation = [[AbstractNavigationController alloc] initWithRootViewController:view];
    [self.navigationController presentViewController:navigation animated:NO completion:nil];
}

#pragma mark - Other Method

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    if (!backValue) return;
    
    NSArray *array = backValue;
    self.searchStartTime = array[0];
    self.searchEndTime= array[1];
    
    NSString *subTitle = [NSString stringWithFormat:@"以下为%@至%@数据",self.searchStartTime,self.searchEndTime];
    [self setTitle:@"砼方量查询" subtitle:subTitle];
    
    self.stateContentState = 0;
    [self.stateData removeAllObjects];
    [self.tableView removeAllSaveCell];
    [self.tableView reloadData];
    
    //获取时间数据
    [self getJobOrderInfoIsReresh];
}

#pragma mark - 网络获取任务单

- (void)getJobOrderInfoIsReresh
{
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"SCDD_TFLTJ_REPORT_HOME"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"开始日期" value:self.searchStartTime];
    [content addParameterKey:@"截止日期" value:self.searchEndTime];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSMutableArray *firstArray = [NSMutableArray array];
        if(result.resultArray && result.resultArray.count>0){
            for(int i=0;i<result.resultArray.count;i++){
                NSArray *array = [result.resultArray objectAtIndex:i];
                NSDictionary *mDictionary = [array objectAtIndex:0];
                [firstArray addObject:mDictionary];
            }
        }
        
        if(firstArray && firstArray.count>0){
            [self.stateData removeAllObjects];
            [self.stateData addObjectsFromArray:firstArray];
            self.stateContentState = 3;
        } else {
            self.stateContentState = 1;
        }
        [self.tableView reloadData];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.stateContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.stateContentState = 2;
        [self.tableView reloadData];
    }];
}

#pragma mark - 通用模板

- (void)drawScrrollTableCell:(GEObjectValueTableViewCell*)cell indexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *valueArray = [NSMutableArray array];
    NSArray *resultArray = cell.objectValue;
    
    if(resultArray && resultArray.count>0){
        for(int i=0;i<resultArray.count;i++){
            NSArray *array = [resultArray objectAtIndex:i];
            NSDictionary *mDictionary = [array objectAtIndex:0];
            [valueArray addObject:mDictionary];
        }
    }
    
    FXCyclePagerView *pagerView = [[FXCyclePagerView alloc]initWithFrame:CGRectMake(0, 0, SuperWidth, 275)];
    pagerView.isInfiniteLoop = YES;
    pagerView.dataSource = self;
    pagerView.delegate = self;
    [pagerView registerClass:[PMSideStatisticsHomeChartCell class] forCellWithReuseIdentifier:@"PMSideStatisticsHomeChartCell"];
    [cell.contentView addSubview:pagerView];
    pagerView.tagObject = valueArray;
    
    FXPageControl *pageControl = [[FXPageControl alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(pagerView.frame) - 22, CGRectGetWidth(pagerView.frame), 26)];
    pageControl.numberOfPages = 2;
    pageControl.currentPageIndicatorSize = CGSizeMake(8, 8);
    pageControl.currentPageIndicatorTintColor = ThemeColorBlue;
    pageControl.pageIndicatorTintColor = [UIColor colorWithWhite:0.85 alpha:1];
    [pagerView addSubview:pageControl];
    pagerView.viewObject = pageControl;
}

#pragma mark - FXCyclePagerViewDataSource

- (NSInteger)numberOfItemsInPagerView:(FXCyclePagerView *)pageView {
    return 2;
}

- (UICollectionViewCell *)pagerView:(FXCyclePagerView *)pagerView cellForItemAtIndex:(NSInteger)index
{
    NSString *keyValue = [NSString stringWithFormat:@"PMSideStatisticsHomeChartCell-%ld",index];
    PMSideStatisticsHomeChartCell *cell = [self.tableView getCellViewKey:keyValue];
    if(!cell){
        cell = (PMSideStatisticsHomeChartCell*)[pagerView dequeueReusableCellWithReuseIdentifier:@"PMSideStatisticsHomeChartCell" forIndex:index];
        [cell setArrayValue:pagerView.tagObject index:index];
        [self.tableView setCellView:cell key:keyValue];
    }
    
    return cell;
}

- (FXCyclePagerViewLayout *)layoutForPagerView:(FXCyclePagerView *)pageView
{
    FXCyclePagerViewLayout *layout = [[FXCyclePagerViewLayout alloc] init];
    layout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width, 270);
    layout.itemHorizontalCenter = YES;
    return layout;
}

- (void)pagerView:(FXCyclePagerView *)pageView didScrollFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex
{
    FXPageControl *pageControl = pageView.viewObject;
    pageControl.currentPage = toIndex;
    //[_pageControl setCurrentPage:newIndex animate:YES];
    NSLog(@"%ld ->  %ld",(long)fromIndex,toIndex);
}


#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 2) {
        if(self.stateContentState == 0) return 1;
        else if(self.stateContentState == 1) return 1;
        else if(self.stateContentState == 2) return 1;
        else if(self.stateContentState == 3) return self.stateData.count;
    }
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        NSString *identifier = [NSString stringWithFormat:@"PMSideStatisticsHomeCellTwo"];
        PMSideStatisticsHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[PMSideStatisticsHomeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifierTwo:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        CGFloat fhflValue = 0;
        CGFloat scflValue = 0;
        CGFloat qsflValue = 0;
        for(int i=0;i<self.stateData.count;i++){
            NSDictionary *mDictionary = [self.stateData objectAtIndex:i];
            fhflValue += [mDictionary objectFormatFloatForKey:@"发货方量" retain:1 except:1];
            scflValue += [mDictionary objectFormatFloatForKey:@"生产方量" retain:1 except:1];
            qsflValue += [mDictionary objectFormatFloatForKey:@"签收方量" retain:1 except:1];
        }
        cell.scflLabel.text = [NSString stringWithFormat:@"%0.1f",scflValue];
        cell.fhflLabel.text = [NSString stringWithFormat:@"%0.1f",fhflValue];
        cell.qsflLabel.text = [NSString stringWithFormat:@"%0.1f",qsflValue];
        
        //（签收方量-生产方量>0）= 盈利
        CGFloat ykflValue = qsflValue - scflValue;
        if(ykflValue<=0){
//            cell.ksflLabel.text = [NSString stringWithFormat:@"%0.1f",fabs(ykflValue)];
            cell.ylflLabel.text = @"0.0";
        } else {
//            cell.ksflLabel.text = @"0.0";
            cell.ylflLabel.text = [NSString stringWithFormat:@"%0.1f",fabs(ykflValue)];
        }
        
        return cell;
            
    } else if(indexPath.section == 1){
        //绘制图表数据
        GEProgressBarTableViewCell *progressBarCell = [self.tableView getCellViewInRow:0 inSection:indexPath.section];
        if (progressBarCell == nil) {
            NSString *identifierBar = [NSString stringWithFormat:@"MCGEProgressBarTableViewCell%ld",indexPath.section];
            progressBarCell = [[GEProgressBarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierBar];
            progressBarCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [self.tableView setCellView:progressBarCell inRow:0 inSection:indexPath.section];
        }
        
        //存在数据绘制图表
        if (progressBarCell.objectValue) {
            NSString *identifier = [NSString stringWithFormat:@"MCChargeInDetailViewController%ld",(long)indexPath.section];
            GEObjectValueTableViewCell *cell = [self.tableView getCellViewKey:identifier];
            if (cell == nil) {
                cell = [[GEObjectValueTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                [self.tableView setCellView:cell key:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.objectValue = progressBarCell.objectValue;
                [self drawScrrollTableCell:cell indexPath:indexPath];
            }
            return cell;
        }
        
        NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
        [parameter setObject:self.searchStartTime forKey:@"开始日期"];
        [parameter setObject:self.searchEndTime forKey:@"截止日期"];
        [progressBarCell getNetWorkDataTableView:tableView moduleType:@"SCDD_TFLTJ_REPORT_HOME" parameter:parameter StationID:0 index:indexPath.section];
        return progressBarCell;
        
    } else if (indexPath.section == 2) {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityIndicat"];
        cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 55);
        
        if(self.stateContentState == 0) {//加载进度条
            UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            act.center = CGPointMake(SuperWidth/2, 26.5);
            act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
            act.hidesWhenStopped = YES;
            [act startAnimating];
            [cell.contentView addSubview:act];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        } else if(self.stateContentState == 1){//显示无数据提示
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"暂无数据";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        } else if(self.stateContentState == 2){//显示失败提示
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"加载数据失败，点击重试";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
            return cell;
            
        } else {
            NSString *identifier = [NSString stringWithFormat:@"PMSideStatisticsHomeCell"];
            PMSideStatisticsHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                cell = [[PMSideStatisticsHomeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            //实际消耗用量
            NSDictionary *mDictionary = [self.stateData objectAtIndex:indexPath.row];
            cell.stationLabel.text = [mDictionary objectFormatStringForKey:@"站点名称" defaults:@"未知"];
            cell.fhflItemLabel.text = [mDictionary objectFormatFloatStringForKey:@"发货方量" retain:1 format:@"%@"];
            cell.qsflItemLabel.text = [mDictionary objectFormatFloatStringForKey:@"签收方量" retain:1 format:@"%@"];
            
            CGFloat scflValue = [mDictionary objectFormatFloatForKey:@"生产方量" retain:1 except:1];
            CGFloat qsflValue = [mDictionary objectFormatFloatForKey:@"签收方量" retain:1 except:1];
            cell.scflItemLabel.text = [NSString stringWithFormat:@"%0.1f",scflValue];
             cell.qsflItemLabel.text = [NSString stringWithFormat:@"%0.1f",qsflValue];
            //（签收方量-生产方量>0）= 盈利
            CGFloat ykflValue = qsflValue - scflValue;
            if(ykflValue<=0){
                cell.ksflItemLabel.text = [NSString stringWithFormat:@"%0.1f方",fabs(ykflValue)];
                cell.ylflItemLabel.text = @"0.0方";
            } else {
                cell.ksflItemLabel.text = @"0.0方";
                cell.ylflItemLabel.text = [NSString stringWithFormat:@"%0.1f方",fabs(ykflValue)];
            }
            
            return cell;
        }
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor colorWithWhite:0 alpha:0.55];
    lable.font = [UIFont boldSystemFontOfSize:15];
    
    if(section == 0){
        lable.text = @"全站砼方量汇总";
    } else if(section == 1){
        lable.text = @"全站砼方量分析";
    } else if (section == 2) {
        lable.text = @"各站点砼方量";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0){
        return 66;
    } else if(indexPath.section == 1){
        return 280;
    } else if(indexPath.section == 2){
        if(self.stateContentState == 3) return 60;
        else return 55;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(indexPath.section == 2){
        if(self.stateContentState == 2) {//加载失败执行
            self.stateContentState = 0;
            [self.tableView reloadData];
            [self getJobOrderInfoIsReresh];
            
        } else if(self.stateContentState == 3){//加载成功，跳转页面
            NSDictionary *mDictionary = [self.stateData objectAtIndex:indexPath.row];
            NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:mDictionary];
            [data setObject:self.searchStartTime forKey:@"开始时间"];
            [data setObject:self.searchEndTime forKey:@"截止日期"];
            
            PMSideStatisticsViewController *viewController = [[PMSideStatisticsViewController alloc] initWithValue:data];
            [self.navigationController pushViewController:viewController animated:YES];
        }
    }
}

@end

